package org.hyjiacan.jcapture.deadqq.client.util;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Window {
	private JFrame win;
	private Rectangle screen;
	private Dimension size;
	private JLabel preview;
	private JDialog tips;
	private JLabel tposx, tposy;

	public Window() {
		init();
	}

	private void init() {
		try {
			win = new JFrame();
			Color tbg = new Color(1f, 0.76f, 0.52f, 0.8f);

			tposx = new JLabel();
			tposy = new JLabel();
			tips = new JDialog();
			tips.setLayout(new FlowLayout());
			tips.setUndecorated(true);
			tips.getContentPane().setBackground(tbg);
			tips.setAlwaysOnTop(true);
			tips.setSize(80, 48);
			tips.setVisible(true);
			tips.add(tposx);
			tips.add(tposy);

			new Robot();
			size = win.getToolkit().getScreenSize();
			screen = new Rectangle(size);
			preview = new JLabel();
			preview.setBorder(BorderFactory.createLineBorder(Color.RED));

			win.setLayout(null);
			win.add(preview);
			win.setAlwaysOnTop(true);
			win.setUndecorated(true);
			win.setOpacity(0.2f);
			win.setBounds(screen);
			win.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
			win.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
						System.exit(0);
					}
				}
			});
			win.addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosed(WindowEvent e) {
					tips.dispose();
				}
			});
			win.setVisible(true);
			win.validate();

		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	public JFrame getWindow() {
		return win;
	}

	public void setListener(CaptureObserver obs) {
		win.addMouseListener(obs);
		win.addMouseMotionListener(obs);
	}

	public void setTipsPosition(Point p) {
		tposx.setText("X坐标:" + p.x);
		tposy.setText("Y坐标:" + p.y);
		tips.setLocation(p);
		tips.repaint();
	}

	public void validate() {
		win.validate();
	}

	public void drawRect(Rectangle rect) {

		preview.setBounds(rect);
		win.validate();
	}

	public void setVisible(boolean b) {
		win.setVisible(b);
	}

	public void hideTips() {
		tips.dispose();
	}

	public Rectangle shoot() {
		return preview.getBounds();
	}
}
